//
//  OAuthViewController.swift
//  sinaWeibo
//
//  Created by 浅爱 on 16/3/14.
//  Copyright © 2016年 y. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    @objc private func defaultAccount() {
        
        // 在webView中设置账号和密码
        let jsStr = "document.getElementById('userId').value = 'shallowlove21@gmail.com', document.getElementById('passwd').value = 'ay611421'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsStr)
        
    }
    
    override func loadView() {
        
        view = webView
        
        // 去掉webView下面的黑条
        view.opaque = false
        
        // 设置代理
        webView.delegate = self
        
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        // 设置导航条
        setNavBar()
        
        // 手写的modal背景色为透明
        view.backgroundColor = UIColor.whiteColor()
        
        // 加载授权页面
        oauthLoadPage()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        
        SVProgressHUD.dismiss()
        
    }
    
    private func setNavBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .Plain, target: self, action: "defaultAccount")
        
    }
    
    
    // 授权页面
    private func oauthLoadPage() {
        
        // 1.urlString
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)" + "&redirect_uri=\(redirect_uri)"
        
        // 2.URL
        let url = NSURL(string: urlString)
        
        // 3.NSUrlRequest
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    
}

// 类扩展  代理
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    
    // 一般协议方法 返回值为bool类型  默认返回true，相对应控件能够正常工作，反之，不能
    // 在此协议方法中，可以监测到webView每次加在新的页面所发起的网络请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else {
            
            
            return false
            
        }
        
        // 不加载页面
        // 回调地址的url中一定包含了code字段
        if urlString.containsString("code") {
            
            // 截取URL中的code字段，获取token
            guard let query = request.URL?.query else {
                
                
                return false
                
            }
            
            let codeStr = "code="
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            // 使用code获取 token
            userAccount.sharedAccount.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                if !isSuccess {
                    
                    SVProgressHUD.showErrorWithStatus(AppErrorTip)
                    
                    
                    return
                    
                }
                
                // 登录成功，销毁当前页
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    
                    // 切换根视图控制器
                    // 通知是同步的
                    NSNotificationCenter.defaultCenter().postNotificationName(switchRootViewController, object: "oauth")
                    
                })
                
            })
            
            
            return false
            
        }
        
        
        return true
        
    }
    
}






